package drrr.controller;

import com.opensymphony.xwork2.ActionContext;
import drrr.orm.RoomEntity;
import drrr.orm.RoomMemberEntity;
import drrr.orm.UserEntity;
import org.apache.struts2.ServletActionContext;

import java.util.Map;

/**
 * Created by lirance on 15/5/21.
 * 退出房间
 */
public class ExitRoomAction extends BaseAction {

    @Override
    public String execute() throws Exception {
        Map<String, Object> session = ServletActionContext.getContext().getSession();
        RoomMemberEntity roomMemberEntity = (RoomMemberEntity) session.get("member");
        RoomEntity roomEntity = (RoomEntity) session.get("room");

        //从roomMember删除当前用户
        getAllService().getRoomService().execute("DELETE FROM roomMember WHERE (memberId=" + roomMemberEntity.getMemberId()+" AND roomId="+ roomMemberEntity.getRoomId()+")");

        //更新房间人数
        String roomOnline=String.format("roomOnline%s",roomEntity.getId()+"");
        int onlineNum = (int) ActionContext.getContext().getApplication().get(roomOnline)-1;

        ActionContext.getContext().getApplication().put(roomOnline, onlineNum);
        int userid = ((UserEntity) session.get("user")).getId();
        int ownerid = roomEntity.getOwner();
        int type = roomEntity.getType();

        if ((userid == ownerid) && (type == 2)) {  //临时房间房主离开，房间被销毁

           return ERROR;
        }
        return SUCCESS;
    }
}
